home *** CD-ROM | disk | FTP | other *** search
- Path: io.salford.ac.uk!aber!not-for-mail
- From: auj@aber.ac.uk (Alun "Penguin" Jones)
- Newsgroups: comp.lang.c
- Subject: Re: Examples of using "volatile"?
- Date: 19 Jan 1996 14:45:49 -0000
- Organization: Prifysgol Cymru (University of Wales) Aberystwyth
- Message-ID: <4doaqt$jnd@osfa.aber.ac.uk>
- References: <4djoj2$mr1@post.gsfc.nasa.gov>
- NNTP-Posting-Host: osfa.aber.ac.uk
-
- Further up the screen Stephen.Maher@gsfc.nasa.gov (Stephen Maher) wrote:
- >
- >I understand the *theory* behind volatile (e.g., to avoid unwanted
- >side-effects?). I also realize it's probably implementation
- >dependent. But some examples from any implementation should help me
- >understand its use a little better.
-
- Here's an example, the like of which happened to me some while back. The
- exact example was using a handler to catch a hardware interrupt. But
- signal() can give the same effect:
-
- #include <signal.h>
- int i=1;
- void interrupt(int sig)
- {
- i = 0;
- return;
- }
-
- int main(void)
- {
- signal(SIGINT, interrupt);
-
- while (i);
- return 0;
- }
-
- In this case, we loop until i becomes zero, which happens when something
- generates SIGINT (^C on Unix should do the job). If i is not volatile,
- then the compiler is free to opt to keep i in a register. When the
- signal occurs, the handler function will write to the memory copy of i,
- but this might not be seen by the main loop if the memory access has
- been optimised out.
-
- So, depending on your compiler/optimisation level, you've either got an
- infinite loop, or you haven't. Specifying i as volatile prevents the
- optimisation of the while loop, and therefore guarantees the action of
- the program.
-
- Dec's compiler on OSF exhibits this behaviour by acting differently for
- -O3 from when no optimisation is specified. Acorn's compiler performs
- the optimisation by default (and this is where I got bitten).
-
- Cheers,
- Alun.
- --
- $_='\=*Sxw!jds@j$.jl.dt#Rw%^dcn"K1x(=Bl1nwl!\*1enab^h"F=!J$h%fhcq',
- tr&J-ZA-Ij-za-i&A-Za-z&&s&\(&logic&&&s&\*&un&g&s&=&al&g&s&\^&it&g&&
- s&%&st&g&&s&\$&ber&g&s&\#&\n&&s&"& of&g,s&([A-Z])& $1&g&&s&\\u&U&&&
- s&!&es, &g&s&\\a&A&&s&1&i&g&&print" $_\n";sub liminal{"use perl!";}
-